import express from "express";
import ServiceBase from "./ServiceBase";
import fabric from 'fabric';
import { JSDOM } from 'jsdom';
import { createCanvas, loadImage } from 'canvas';
import fs from 'fs';
import path from 'path';
import urlparse from 'url-parse';

// ai上面的代码不能动↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑

export default class FabricService extends ServiceBase {

    constructor(req: express.Request = {} as express.Request, res: express.Response = {} as express.Response) {
        super(req, res);
    }

    // ai上面的代码不能动
    // 转换fabric JSON为图片的核心方法
    convert_fabric_json_to_image = async (fabricJson: any, width: number, height: number, outputFormat: string = 'png', quality: number = 1.0) => {
        // 1. 伪造DOM环境 → 让Fabric以为自己在浏览器里
        const dom = new JSDOM('<!DOCTYPE html><html><body></body></html>', { resources: 'usable' });
        // 临时保存原始的全局对象
        const originalWindow = global.window;
        const originalDocument = global.document;
        const originalHTMLCanvasElement = global.HTMLCanvasElement;
        const originalImage = global.Image;

        // 设置全局对象
        (global as any).window = dom.window;
        (global as any).document = dom.window.document;
        (global as any).HTMLCanvasElement = dom.window.HTMLCanvasElement;
        (global as any).Image = dom.window['Image'];

        try {
            // 2. 创建node-canvas实例
            //@ts-ignore
            const nodeCanvas = createCanvas(width, height) as any;
            // 补一个 hasAttribute 空函数，让 Fabric 5 不再报错
            nodeCanvas.hasAttribute = () => false;
            nodeCanvas.style = {};
            nodeCanvas.setAttribute = () => { };
            nodeCanvas.classList = { add: () => { } };

            // 3. 创建fabric.StaticCanvas实例
            const canvas = new fabric.StaticCanvas(nodeCanvas, {
                width: width,
                height: height
            });
            
            // 4. 加载fabric JSON数据
            await canvas.loadFromJSON(fabricJson, () => {
                canvas.renderAll();
            });

            // 5. 生成图片数据URL
            let dataUrl: string;
            if (outputFormat === 'jpeg' || outputFormat === 'jpg') {
                dataUrl = canvas.toDataURL({ format: 'jpeg', quality: quality, multiplier: 1 });
            } else {
                dataUrl = canvas.toDataURL({ format: 'png', multiplier: 1 });
            }

            // 返回生成的图片数据和相关信息
            return {
                dataUrl,
                width,
                height,
                objectCount: fabricJson.objects ? fabricJson.objects.length : 0,
                outputFormat
            };
        } finally {
            // 恢复原始的全局对象，避免污染
            (global as any).window = originalWindow;
            (global as any).document = originalDocument;
            (global as any).HTMLCanvasElement = originalHTMLCanvasElement;
            (global as any).Image = originalImage;
        }
    };

    // 生成fabric效果图
    generate_fabric_image = async (params: Record<string, any>) => {
        // 参数校验
        this.verifyParams(['fabricJson', 'width', 'height']);

        const { fabricJson, width, height, outputFormat = 'png', quality = 1.0 } = params;

        // 调用抽离的核心方法
        return await this.convert_fabric_json_to_image(fabricJson, width, height, outputFormat, quality);
    };
}

// 类已在定义时导出